/*******************************************************************************
 * Copyright 2011 Towee.net
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package net.towee.client.widgets;

import com.google.gwt.dom.client.UListElement;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Widget;

public class UnorderedListWidget extends AbsolutePanel {
	public UnorderedListWidget() {
		super(DOM.createElement("UL"));
	}

	public void setId(String id) {
		// Set an attribute common to all tags
		getElement().setId(id);
	}

	public void setDir(String dir) {
		// Set an attribute specific to this tag
		((UListElement) getElement().cast()).setDir(dir);
	}
	public void addBefore(Widget child, Element before) {
		// Detach new child.
		child.removeFromParent();

		// Logical attach.
		getChildren().add(child);

		// Physical attach.
		DOM.insertBefore(getElement(), child.getElement(), before);

		// Adopt.
		adopt(child);
	}

	public void addFirst(Widget child) {
		addBefore(child, (Element) this.getElement().getFirstChildElement());
	}

	public void add(Widget w) {
		// Detach new child.
		w.removeFromParent();

		// Logical attach.
		getChildren().add(w);

		// Physical attach.
		DOM.insertChild(getElement(), w.getElement(), getWidgetCount() + 1);

		// Adopt.
		adopt(w);
	}
	
	public ListItemWidget addItem(String string) {
		ListItemWidget item = new ListItemWidget(string);
		add(item);

		return item;
	}

	public void addClickHandler(ClickHandler handler) {
		for (int i = 0; i < getWidgetCount(); i++) {
			if (getWidget(i) instanceof ListItemWidget)
				((ListItemWidget) getWidget(i)).addClickHandler(handler);
		}
	}
}